import { Component, OnInit, Inject } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material';
import { StepConfig } from '../../model/step-config.model';
import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms';
import { GetConfigService } from '../../services/get-config/get-config.service';

@Component({
  selector: 'app-add-step',
  templateUrl: './add-step.component.html',
  styleUrls: ['./add-step.component.css']
})
export class AddStepComponent implements OnInit {
  formGroup: FormGroup;

  actions = [];
  actionNames = [];
  modes = [];
  actionArgs: any = [];
  groupSetting = {
    action: new FormControl('', Validators.required),
  };

  constructor(
    @Inject(MAT_DIALOG_DATA) public stepConfig: StepConfig,
    private dialogRef: MatDialogRef<AddStepComponent>,
    private fb: FormBuilder,
    private getconfig: GetConfigService,
  ) {
  }

  ngOnInit() {
    this.getconfig.actions.subscribe((json: any) => {
      if (json.data) {
        this.actions = json.data;
        this.actionNames = Object.keys(json.data).sort((a, b) => a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1);
        const {title, ...restConfig} = this.stepConfig;
        if (restConfig.stepNo !== undefined) {
          const {stepNo, ...config} = restConfig;
          this.selectAction(this.actions[config.action]);
          this.formGroup.setValue(config);
        } else {
          this.formGroup.setValue({action: null});
        }
      } else {
        this.actions = [];
      }
    });
    this.getconfig.modes.subscribe((json: any) => this.modes = json.data);
    this.formGroup = this.fb.group(this.groupSetting);
  }

  submit() {
    if (this.formGroup.valid) {
      this.dialogRef.close(this.formGroup.getRawValue());
    }
  }

  selectAction(args) {
    if (args) {
      Object.entries(args).forEach((arg: any) => {
        this.groupSetting[arg[0]] = new FormControl('', Validators.required);
      });
      this.formGroup = this.fb.group(this.groupSetting);
      this.actionArgs = Object.entries(args);
    }
  }
}
